﻿using System;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web.Mvc;
using UscSunShine.Models;
using PagedList;
using UscSunShine.ViewModels.ExtensionMethod;
using System.Collections.Generic;
using System.ComponentModel;


namespace UscSunShine.Mvc.Areas.Admin.Controllers
{
    [Description("申请信息管理类")]
    public class RequestManageController : UscSunShine.Mvc.Controllers.BaseController
    {

        private ApplicationDbContext db = new ApplicationDbContext();
        //分页页面记录数
        private const int pageSize = 10;


        /// <summary>
        /// 管理后台用的列表
        /// </summary>
        /// <param name="departmentID"></param>
        /// <param name="requestCategory"></param>
        /// <param name="titleSearchString"></param>
        /// <param name="acceptNumberSearchString"></param>
        /// <param name="currentDepartmentID"></param>
        /// <param name="currentCategory"></param>
        /// <param name="currentTitle"></param>
        /// <param name="currentNumber"></param>
        /// <param name="page"></param>
        /// <returns></returns>        
        [Description("申请信息列表")]
        public ActionResult Index(
            int? departmentID,
            RequestCategory? requestCategory,
            string titleSearchString,
            string acceptNumberSearchString,
            int? currentDepartmentID,
            RequestCategory? currentCategory,
            string currentTitle,
            string currentNumber,
            int? page)
        {
            //取当前用户的学院
            var username = ControllerContext.HttpContext.User.Identity.Name;
            var user = db.Users.FirstOrDefault(t => t.UserName == username);
            if (user == null)
            {
                return Content("请重新登录");
            }
            var departmentIds = user.Departments.Select(t => t.DepartmentId);
            //取允许查看的数据
            var requests = RequestsCanBrowse(departmentIds);
            //根据部门ID筛选
            if (departmentID != null)
            {
                requests = requests.Where(t => t.DepartmentID == departmentID);
                currentDepartmentID = departmentID;
            }
            else if (currentDepartmentID != null)
            {
                requests = requests.Where(t => t.DepartmentID == currentDepartmentID);
                departmentID = currentDepartmentID;
            }
            //根据类别筛选
            if (requestCategory.HasValue)
            {
                requests = requests.Where(t => t.RequestCategory == requestCategory);
                currentCategory = requestCategory;
            }
            else if (currentCategory.HasValue)
            {
                requests = requests.Where(t => t.RequestCategory == currentCategory);
                requestCategory = currentCategory;
            }
            //根据查询关键字筛选
            if (titleSearchString != null)
            {
                page = 1;
            }
            else
            {
                titleSearchString = currentTitle;
            }
            if (acceptNumberSearchString != null)
            {
                page = 1;
            }
            else
            {
                acceptNumberSearchString = currentNumber;
            }
            //保存当前状态
            ViewBag.currentTitle = titleSearchString;
            ViewBag.currentCategory = requestCategory;
            ViewBag.currentDepartmentID = departmentID;
            ViewBag.currentNumber = acceptNumberSearchString;
            ViewBag.departmentID = new SelectList(db.Departments.Where(t => departmentIds.Contains(t.ID)), "ID", "Name", departmentID);

            if (requestCategory.HasValue)
            {
                ViewBag.requestCategory = new SelectList(EnumExtension.GetSelectList(typeof(RequestCategory)), "Value", "Text", requestCategory.Value);
            }
            else
            {
                ViewBag.requestCategory = new SelectList(EnumExtension.GetSelectList(typeof(RequestCategory)), "Value", "Text");
            }
            //根据查询关键字筛选数据
            if (!string.IsNullOrWhiteSpace(titleSearchString))
            {
                requests = requests.Where(t => t.Title.Contains(titleSearchString));
            }
            //根据受理单号查询
            if (!string.IsNullOrWhiteSpace(acceptNumberSearchString))
            {
                requests = db.Requests.Where(t => t.AcceptNumber == acceptNumberSearchString);
            }

            requests = requests.OrderByDescending(t => t.AcceptDate);


            var pageNumber = (page ?? 1);

            return View(requests.ToPagedList(pageNumber, pageSize));
        }


        /// <summary>
        /// 取允许浏览的数据
        /// </summary>
        /// <returns></returns>
        private IQueryable<Request> RequestsCanBrowse(IEnumerable<int> departmentIds)
        {
            //取允许浏览的处理状态
            var status = UscSunShine.Models.Request.StatusCanBrowse;
            //取数据
            //未审核的不显示
            var requests = db.Requests.Include(t => t.Department)
                                      .Where(t =>
                                          status.Contains(t.ProcessStatus) && //审核状态
                                          departmentIds.Contains(t.DepartmentID));//责任部门
            return requests;
        }

        // GET: /Request/Details/5
        [Description("申请信息详情")]
        public async Task<ActionResult> Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Request request = await db.Requests.Include(t => t.Department)
                                               .SingleAsync(t => t.ID == id);
            if (request == null)
            {
                return HttpNotFound();
            }
            ////点击次数累加
            //request.ViewTimes += 1;
            //await db.SaveChangesAsync();
            return View(request);
        }

        // GET: /Request/Edit/5
        //回复申请
        [Description("回复申请信息")]
        public async Task<ActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            Request request = await db.Requests.Include(t => t.Department)
                                               .SingleAsync(t => t.ID == id);

            if (request == null)
            {
                return HttpNotFound();
            }
            //处理日期是否为空
            if (!request.ProcessDate.HasValue)
            {
                request.ProcessDate = DateTime.Now;
            }

            //ViewBag.DepartmentID = new SelectList(db.Departments.Where(t => departmentIds.Contains(t.ID)), "ID", "Name", request.DepartmentID);
            //ViewBag.RequestCategory = new SelectList(EnumExtension.GetSelectList(typeof(RequestCategory)), "Value", "Text", (int)request.RequestCategory);
            //ViewBag.ProcessStatus = new SelectList(EnumExtension.GetSelectList(typeof(UscSunShine.Models.ProcessStatus)), "Value", "Text", (int)request.ProcessStatus);
            return View(request);
        }

        // POST: /Request/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。
        // 回复申请
        [Description("回复申请信息，保存")]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Edit([Bind(Include = "ID,DepartmentID,RequestCategory,ProcessStatus,AcceptNumber,Title,Content,Username,ContactPhone,Email,ExpectResolveDate,AcceptDate,AuditDate,ViewTimes,RespondContent,ProcessDate")] Request request)
        {
            if (ModelState.IsValid)
            {
                request.Process();
                db.Entry(request).State = EntityState.Modified;
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            return View(request);
        }
        
        
    }
}
